<template>
  <div class="container">
    <SearchBox ref="searchRef" :searchValue="searchValue" @search="search" />
    <div class="table-operations">
      <a-button @click="handleAdd()">新增活动</a-button>
    </div>
    <tableData
      :tableList="tableList"
      @changePagination="changePagination"
      :pagination="pagination"
      @openEdit="openEdit"
      @handleUpdate="handleUpdate"
      @openGoodEdit="openGoodEdit"
      @handleDelete="handleDelete"
    />
  </div>
  <edit-modal ref="editModalRef" @update="handleUpdate" @cancel="handleCancel" />
  <EditDrawModal
    @handlePushSelectDrawList="handlePushSelectDrawList"
    @handleOutSelectDrawList="handleOutSelectDrawList"
    ref="editEditDrawModalRef"
    :selectDrawList="selectDrawList"
  />
</template>
<style lang="stylus" scoped>

.container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
  padding 10px

}
</style>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import editModal from './components/activeView/editModal.vue'
import EditDrawModal from './components/activeView/editDrawModal.vue'
import tableData from './components/activeView/tableData.vue'
import type { TTable, TSearch } from './components/activeView/type.dict'
import SearchBox from './components/activeView/searchBox.vue'

import { message } from 'ant-design-vue'
import { listActives, createActive, updateActive, deleteActive, getActiveDetail } from '@/api/active.api'
import type { CreateAdminActiveDto, UpdateAdminActiveDto, ActivePoolItem } from '@/types/active.api'

const searchRef = ref()

//初始化SDK实例
const tableList = ref<TTable[]>([])

const pagination = ref<{
  total: number
  current: number
  pageSize: number
}>({
  total: 0,
  current: 1,
  pageSize: 10,
})
const searchValue = ref<TSearch>({
  name: '',
  status: '',
  progress: '',
})
const editModalRef = ref()
const editEditDrawModalRef = ref()
const selectDrawList = ref<ActivePoolItem[]>([])
// 打开编辑弹窗
const openEdit = (record: TTable) => {
  editModalRef.value.open(record)
}

const openGoodEdit = async (record: TTable) => {
  await getDetails(record._id)
  editEditDrawModalRef.value.open(record)
}

const getDetails = async (id: string) => {
  try {
    const { code, data, message: msg } = await getActiveDetail(id)
    if (code === 200 && data) {
      const pool = data.pool ?? []
      const mapped: ActivePoolItem[] = pool
      // 分页：固定第一页，取 10 条
      selectDrawList.value = mapped
    } else {
      message.error(msg || '获取详情失败')
    }
  } catch (err) {
    console.log(err)
    message.error('获取详情失败')
  }
}
const handlePushSelectDrawList = (record: ActivePoolItem) => {
  console.log(record)
  selectDrawList.value.push(record)
}
const handleAdd = () => {
  // 处理新增逻辑
  editModalRef.value.open()
}
const handleOutSelectDrawList = (record: ActivePoolItem) => {
  getLis()
  selectDrawList.value = selectDrawList.value.filter((item: ActivePoolItem) => item.draw._id !== record.draw._id)
}
// 处理新增/更新
const handleUpdate = async (record: TTable) => {
  const isEditMode = !!record._id
  try {
    if (isEditMode) {
      const dto: UpdateAdminActiveDto = {
        // 来自编辑弹窗或表格状态切换；可选字段按需传递
        name: record.name ?? undefined,
        status: record.status,
        progress: record.progress ?? undefined,
        price: record.price ?? undefined,
        tag: record.tag ?? undefined,
        cover: record.cover ?? undefined,
        use_num: record.use_num ?? undefined,
      }
      const { code, message: msg } = await updateActive(record._id, dto)
      if (code === 200) {
        message.success('编辑成功')
        getLis()
      } else {
        message.error(msg || '编辑失败')
      }
    } else {
      const dto: CreateAdminActiveDto = {
        name: (record.name as string),
        status: record.status,
        progress: (record.progress as string),
        price: (record.price as number),
        tag: record.tag ?? [],
        cover: (record.cover as string),
        use_num: record.use_num ?? 0,
      }
      const { code, message: msg } = await createActive(dto)
      if (code === 200) {
        message.success('新增成功')
        getLis()
      } else {
        message.error(msg || '新增失败')
      }
    }
  } catch (err) {
    console.log(err)
  }
}

// 删除
const handleDelete = async (record: TTable) => {
  try {
    const { code, message: msg } = await deleteActive(record._id)
    if (code === 200) {
      message.success('删除成功')
      getLis()
    } else {
      message.error(msg || '删除失败')
    }
  } catch (err) {
    console.log(err)
  }
}

const handleCancel = () => {
  // 取消操作
}
// 搜索操作
const search = (searchVal: TSearch) => {
  searchValue.value = { ...searchValue.value, ...searchVal }
  pagination.value.current = 1
  getLis()
}

const getLis = async () => {
  try {
    const { code, data, message: msg } = await listActives({
      name: searchValue.value.name || undefined,
      status: searchValue.value.status || undefined,
      progress: searchValue.value.progress || undefined,
      page: pagination.value.current,
      size: pagination.value.pageSize,
    })
    if (code === 200 && data) {
      pagination.value.total = (data.total as number) ?? data.list.length
      tableList.value = (data.list as unknown as TTable[])
    } else {
      message.error(msg || '获取列表失败')
    }
  } catch (err) {
    console.log(err)
  }
}
const changePagination = (paginations: { current: number; pageSize: number }) => {
  pagination.value.current = paginations.current
  pagination.value.pageSize = paginations.pageSize
  getLis()
}
onMounted(() => {
  getLis()
})
</script>
